﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Windows.Forms;

namespace intTrans
{
    class TempMedianFilter
    {
        private Bitmap[] BitPics;
        private Bitmap BitPic;
        int[] unsortedR;
        int[] unsortedG;
        int[] unsortedB;
        Color computedColor;
     
        public TempMedianFilter(string[] filenames)
        {
            BitPics = new Bitmap[filenames.Length];
            for (int i = 0; i < filenames.Length; i++)
            {
                BitPics[i] = new Bitmap(filenames[i]);
                if (BitPics[i].Width != BitPics[0].Width || BitPics[i].Height != BitPics[0].Height) throw new Exception("size error"); 
            }
            BitPic = new Bitmap(BitPics[0].Width, BitPics[0].Height);
        }

        public Bitmap Transform(ProgressBar progbar)
        {            
            progbar.Maximum = BitPic.Width;
            progbar.Value = 0;
            unsortedR = new int[BitPics.Length];
            unsortedG = new int[BitPics.Length];
            unsortedB = new int[BitPics.Length];
            for (int i = 0; i < BitPic.Width; ++i)
            {
                for (int j = 0; j < BitPic.Height; ++j)
                {
                    for (int PicInd = 0; PicInd < BitPics.Length; PicInd++)
                    {
                        unsortedR[PicInd] = BitPics[PicInd].GetPixel(i, j).R;
                        unsortedG[PicInd] = BitPics[PicInd].GetPixel(i, j).G;
                        unsortedB[PicInd] = BitPics[PicInd].GetPixel(i, j).B;
                    }
                    Array.Sort(unsortedR);
                    Array.Sort(unsortedG);
                    Array.Sort(unsortedB);
                    if (unsortedR.Length % 2 == 0)
                    {
                        computedColor = Color.FromArgb((unsortedR[(unsortedR.Length / 2) -1] + unsortedR[unsortedR.Length / 2])/2,
                                    (unsortedG[(unsortedG.Length / 2) -1] + unsortedG[unsortedG.Length / 2 ])/2,
                                    (unsortedB[(unsortedB.Length / 2) -1] + unsortedB[unsortedB.Length / 2 ])/2);
                    }
                    else
                    {
                        computedColor = Color.FromArgb(unsortedR[(unsortedR.Length-1) / 2],
                                    unsortedG[(unsortedG.Length-1) / 2],
                                    unsortedB[(unsortedB.Length-1) / 2]);
                    }
                    BitPic.SetPixel(i,j,computedColor);
                }
                progbar.Value++;
                
            }
            
            return BitPic;
            
        }
    }
}
